package com.jianghu;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jianghu.helpers.GetLineFromtxt;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class Hottopic extends Activity {
	// private String user;
	private ListView listView;
	private boolean surplus = true;
	private static int count = 0;
	// private Thread mThread;
	private ProgressBar progressBar;
	private ProgressBar progressBarList;
	private TextView txtMore;
	String[] titles = { "科技", "家电", "手机", "图片", "电脑", "新闻", "娱乐", "笑话", "艺术",
			"电影", "音乐", "体育", "汽车", "游戏", "金融", "健康", "旅游", "美食", "时尚", "教育",
			"购物", "其他" };
	Integer[] titlesimgs = { R.drawable.news, R.drawable.news, R.drawable.news,
			R.drawable.news, R.drawable.news, R.drawable.news, R.drawable.play,
			R.drawable.fun, R.drawable.art, R.drawable.movie, R.drawable.music,
			R.drawable.sport, R.drawable.car, R.drawable.game,
			R.drawable.finance, R.drawable.health, R.drawable.plane,
			R.drawable.food, R.drawable.mode, R.drawable.mode, R.drawable.mode,
			R.drawable.mode };
	int titlecount = titles.length;
	int titletype = 0;
	HashMap<Integer, ArrayList<HashMap<String, Object>>> listItemHashMap = new HashMap<Integer, ArrayList<HashMap<String, Object>>>();

	private RadioGroup radioGroup;
	private RadioButton rButton0, rButton1, rButton2, rButton3, rButton4,
			rButton5;
	PopupWindow pop;
	View loadingLayout;
	// SimpleAdapter listItemAdapter;
	ImageAndTextListAdapter adapter;
	ArrayList<HashMap<String, Object>> listItem;

	DownloadMore downloadMore;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hottopic);
		init();

		setTabTitle(0);
		ImageButton home = (ImageButton) findViewById(R.id.homebuttonofusertrends);
		home.setOnClickListener(new homeClickListener());

		ImageButton refresh = (ImageButton) findViewById(R.id.refreshbuttonofusertrends);
		refresh.setOnClickListener(new refreshClickListener());

		listView = (ListView) findViewById(R.id.listViewOfHottopic);
		listItem = new ArrayList<HashMap<String, Object>>();
		loadingLayout = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.footer_listview_user_trends, null, false);
		listView.addFooterView(loadingLayout, null, true);
		refreshListview(titletype);

		rButton5.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pop != null && pop.isShowing()) {
					return;
				}
				LayoutInflater inflater = LayoutInflater.from(Hottopic.this);
				View view = inflater.inflate(R.layout.hottopic_titlelist, null);
				ListView lv = (ListView) view
						.findViewById(R.id.titlelist_listview);
				List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
				for (int i = 5; i < titles.length; i++) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("title", titles[i]);
					map.put("image", titlesimgs[i]);
					datalist.add(map);
				}
				SimpleAdapter adapter = new SimpleAdapter(Hottopic.this,
						datalist, R.layout.hottopic_titlelist_item,
						new String[] { "title", "image" },
						new int[] { R.id.titlelist_item_tv,
								R.id.titlelist_item_iv });
				lv.setAdapter(adapter);
				pop = new PopupWindow(view, 120, 300);
				/*
				 * 这里如果不设置Focusable的话,则popwindow里的listview不能选择,
				 * 但是这样的话popwindow外面的其它按钮不可用,是有模式状态
				 */
				pop.setFocusable(true);
				lv.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						pop.dismiss();
						// 选中的类型
						int position = arg2 + 5;
						titletype = position;
						Log.v("type", titles[position]);
						// refresh listview by type
						rButton5.setText(titles[position]);
						refreshListview(position);
					}
				});
				pop.showAsDropDown(rButton5);
			}
		});
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup radioGroup, int Id) {
				clearPopwindow();
				rButton5.setText("更多");
				count = 0;
				switch (Id) {
				case R.id.radio_button0:
					refreshListview(0);
					break;
				case R.id.radio_button1:
					refreshListview(1);
					break;
				case R.id.radio_button2:
					refreshListview(2);
					break;
				case R.id.radio_button3:
					refreshListview(3);
					break;
				case R.id.radio_button4:
					refreshListview(4);
					break;
				}
			}
		});
	}

	private void refreshListview(int type) {
		// listView.setVisibility(View.INVISIBLE);
		// progressBarList.setVisibility(View.VISIBLE);
		titletype = type;
		if (listItemHashMap.containsKey(type)) {
			listItem = listItemHashMap.get(type);
			adapter = new ImageAndTextListAdapter(Hottopic.this, listItem,
					listView);
			listView.setAdapter(adapter);
		} else {
			if (downloadMore != null
					&& downloadMore.getStatus() == AsyncTask.Status.RUNNING) {
				downloadMore.cancel(true);
			}
			// listView.setAdapter(null);
			listItem.clear();
			count = 0;
			downloadMore = new DownloadMore();
			downloadMore.execute((Void) null);
			// 按照选择的类型获得数据
		}
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent();
				intent.setClass(Hottopic.this, Article.class);

				Hottopic.this.startActivity(intent);
			}
		});

		loadingLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (downloadMore != null
						&& downloadMore.getStatus() == AsyncTask.Status.FINISHED) {
					progressBar = (ProgressBar) loadingLayout
							.findViewById(R.id.progressBarofUserTrends);
					progressBar.setVisibility(View.VISIBLE);
					txtMore = (TextView) loadingLayout
							.findViewById(R.id.moreofusertrends);
					txtMore.setVisibility(View.GONE);
					downloadMore = new DownloadMore();
					downloadMore.execute((Void) null);
				}
			}
		});
	}

	private void loadRemnantListItem(int totalItemCount) {
		// 由 titletype去获得余下的数据
		int max = totalItemCount + 10;
		for (int i = totalItemCount; i < max; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			String str = GetLineFromtxt.readAppointedLineNumber(Hottopic.this,
					i + 1);
			if (str == null) {
				surplus = false;
				Log.v("readover", "over");
				break;
			}
			count++;
			// Log.v("content", "i=" + i + " " + (++abc) + " " + str);
			map.put("comeform", "设计工坊");
			map.put("timeoftrends",
					new SimpleDateFormat("MM-dd HH:mm").format(new Date()));
			map.put("title", "title");
			map.put("contentsoftrends", str);
			listItem.add(map);
		}
		listItemHashMap.put(titletype, listItem);
	}

	class DownloadMore extends AsyncTask<Void, Void, Void> {
		private int pos = 0;

		@Override
		protected void onPreExecute() {
			listView.setVisibility(View.INVISIBLE);
			progressBarList.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			pos = count;
			loadRemnantListItem(count);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// listItemAdapter.notifyDataSetChanged();
			if (surplus == false) {
				listView.removeFooterView(loadingLayout);
			} else {
				progressBar = (ProgressBar) loadingLayout
						.findViewById(R.id.progressBarofUserTrends);
				progressBar.setVisibility(View.GONE);
				txtMore = (TextView) loadingLayout
						.findViewById(R.id.moreofusertrends);
				txtMore.setVisibility(View.VISIBLE);
			}
			adapter = new ImageAndTextListAdapter(Hottopic.this, listItem,
					listView);
			listView.setAdapter(adapter);
			if (pos - 1 >= 0) {
				listView.setSelection(pos - 1);
			} else {
				listView.setSelection(0);
			}
			progressBarList.setVisibility(View.INVISIBLE);
			listView.setVisibility(View.VISIBLE);
			super.onPostExecute(result);
		}
	}

	private void clearPopwindow() {
		if (pop != null && pop.isShowing()) {
			pop.dismiss();
		}
	}

	private void setTabTitle(int i) {
		if (i < titlecount) {
			rButton0.setText(titles[i]);
		} else {
			i = 0;
			rButton0.setText(titles[i]);
		}
		i++;
		if (i < titlecount) {
			rButton1.setText(titles[i]);
		} else {
			i = 0;
			rButton1.setText(titles[i]);
		}
		i++;
		if (i < titlecount) {
			rButton2.setText(titles[i]);
		} else {
			i = 0;
			rButton2.setText(titles[i]);
		}
		i++;
		if (i < titlecount) {
			rButton3.setText(titles[i]);
		} else {
			i = 0;
			rButton3.setText(titles[i]);
		}
		i++;
		if (i < titlecount) {
			rButton4.setText(titles[i]);
		} else {
			i = 0;
			rButton4.setText(titles[i]);
		}
	}

	private void init() {
		radioGroup = (RadioGroup) findViewById(R.id.radio_group);
		rButton0 = (RadioButton) findViewById(R.id.radio_button0);
		rButton1 = (RadioButton) findViewById(R.id.radio_button1);
		rButton2 = (RadioButton) findViewById(R.id.radio_button2);
		rButton3 = (RadioButton) findViewById(R.id.radio_button3);
		rButton4 = (RadioButton) findViewById(R.id.radio_button4);
		rButton5 = (RadioButton) findViewById(R.id.radio_button5);
		progressBarList = (ProgressBar) findViewById(R.id.hot_progressbar);
		rButton5.setText("更多");
	}

	class homeClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(Hottopic.this, MainPage.class);
			Hottopic.this.startActivity(intent);
		}

	}

	class refreshClickListener implements OnClickListener {
		private ProgressDialog progressDialog;

		@Override
		public void onClick(View v) {

			progressDialog = ProgressDialog.show(Hottopic.this, "刷新中..",
					"请稍等...", true, false);
			new Thread() {

				@Override
				public void run() {
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					handlerRefresh.sendEmptyMessage(0);
				}
			}.start();
		}

		private Handler handlerRefresh = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				listView.setSelection(0);
				progressDialog.dismiss();
			}
		};
	}

	public class ImageAndTextListAdapter extends BaseAdapter {

		public class Holder {
			TextView title;
			//, username,  content, time, commentCount, likedCount;
			ImageView image;
			//userImage, commentIamge, likedImage;
		}

		// private ListView listView;
		private ArrayList<HashMap<String, Object>> list;
		private Activity activity;

		// private AsyncImageLoader asyncImageLoader;

		public ImageAndTextListAdapter(Activity activity,
				ArrayList<HashMap<String, Object>> list, ListView listView) {
			// this.listView = listView;
			this.list = list;
			this.activity = activity;
			// asyncImageLoader = new AsyncImageLoader();
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			// Inflate the views from XML
			View rowView = convertView;
			Holder holder;
			// ViewCache viewCache;
			if (rowView == null) {
				LayoutInflater inflater = activity.getLayoutInflater();
				rowView = inflater.inflate(R.layout.listview_hottopic_trends,
						null);
				holder = new Holder();
				holder.title=(TextView)rowView.findViewById(R.id.hot_article_title);
				holder.image=(ImageView)rowView.findViewById(R.id.hot_article_image);
				//holder.username = (TextView) rowView.findViewById(R.id.hot_ComeFrom);
				//holder.content = (TextView) rowView.findViewById(R.id.contentsoftrends);
				//holder.time = (TextView) rowView.findViewById(R.id.hot_timeoftrends);
				//holder.commentIamge = (ImageView) rowView.findViewById(R.id.comments_image);
				//holder.likedImage = (ImageView) rowView.findViewById(R.id.liked_icon);
				//holder.userImage = (ImageView) rowView.findViewById(R.id.userimage);
				rowView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			final HashMap<String, Object> map = list.get(position);
			// map.put("comeform", "设计工坊");
			// map.put("timeoftrends",
			// new SimpleDateFormat("MM-dd HH:mm").format(new Date()));
			// map.put("title", "title");
			// map.put("contentsoftrends", str);
			if (map != null) {
				holder.title.setText((String)map.get("title"));
				switch (position) {
				case 0:
					rowView.setBackgroundColor(Color.rgb(251, 251, 189));
					holder.image.setBackgroundResource(R.drawable.gold);
					holder.title.setText("龙释涯不愧是散修第一人，带着周雄清一起飞，两天下来，周雄清从老师脸上也没有看到任何疲倦的痕迹。这就是天审，逆天级的存在");
					break;
				case 1:
					rowView.setBackgroundColor(Color.rgb(251, 251, 189));
					holder.image.setBackgroundResource(R.drawable.sliver);
					break;
				case 2:
					rowView.setBackgroundColor(Color.rgb(251, 251, 189));
					holder.image.setBackgroundResource(R.drawable.copper);
					break;
				}
//				holder.username.setText((String) map.get("comefrom"));
//				holder.content.setText((String) map.get("contentsoftrends"));
//				holder.commentIamge.setOnClickListener(new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						Intent intent = new Intent();
//						intent.setClass(activity, Comment.class);
//						activity.startActivity(intent);
//					}
//				});
//				holder.likedImage.setOnClickListener(new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						;
//						Intent intent = new Intent();
//						intent.setClass(activity, Articlesliked.class);
//						activity.startActivity(intent);
//					}
//				});
//				holder.userImage.setOnClickListener(new View.OnClickListener() {
//					@Override
//					public void onClick(View arg0) {
//						Intent intent = new Intent();
//						intent.setClass(activity, UserTrendsManual.class);
//						Bundle bundle = new Bundle();
//						bundle.putString("item", "设计工厂");
//						bundle.putString("type", "trends");
//						intent.putExtras(bundle);
//						activity.startActivity(intent);
//					}
//				});

			}
			return rowView;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
	}
}